package io.github.shenbinglife.springboot2.layui.admin.controller;

import io.github.shenbinglife.springboot2.layui.admin.entity.User;
import io.github.shenbinglife.springboot2.layui.admin.model.UserDetail;
import io.github.shenbinglife.springboot2.layui.admin.service.impl.UserService;
import io.github.shenbinglife.springboot2.layui.common.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    public static final String LOGIN_USER = "login_user";
    public static final String LOGIN_ROLE_ID = "login_role_id";

    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping("login")
    public Result<?> login(String account, String password, HttpSession session) {
        if (userService.login(account, password)) {
            User user = userService.getByAccount(account);
            if (user.getState() == User.UserState.enabled) {
                UserDetail userDetail = userService.getUserDetail(user.getId());
                session.setAttribute(LOGIN_USER, userDetail);
                session.setAttribute(LOGIN_ROLE_ID, userDetail.getRoleIds()
                        .get(0));
                return Result.success();
            } else {
                return Result.failure("登录失败，用户被禁用");
            }
        } else {
            return Result.failure("登录失败，账号密码不正确");
        }
    }

    @GetMapping("logout")
    public String logout(HttpSession session) {
        session.removeAttribute(LOGIN_USER);
        return "redirect:/view/login";
    }
}
